首先,我們可以先從官方的範例 ARC 開始‧
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person?
deinit { print("Apartment \(unit) is being deinitialized") }
}
第一步,我們分別先建立了 john
以及 unit4A
var john: Person? = Person(name: "John Appleseed")
var unit4A: Apartment? = Apartment(unit: "4A")
此時區域變數
便會對物件
建立強引用(Strong Reference)
john
-> Person(name: "John Appleseed")
unit4A
-> Apartment(unit: "4A")
第二步,我們分別對 john
以及 unit4A
分別建立關聯
john?.apartment = unit4A
unit4A?.tennant = john
第三步,斷開區域變數對物件的強引用
john = nil
unit4A = nil
此時兩個物件並沒有被釋放,因為在前一個步驟時已經發生了 retain cycle
解法其實也很簡單,只要將其中一方改為弱引用(weak reference)
class Apartment {
- var tennant: Person?
+ weak var tennant: Person?